<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  Monitor,
  Clock,
  DataLine,
  Warning,
  Fold,
  Platform,
  Expand,
  Location,
  Message,
  InfoFilled,
  WarningFilled,
  CircleCheckFilled,
  CircleCloseFilled,
  HomeFilled,
} from '@element-plus/icons-vue'
import { useRoomConfigStore } from '@/store/roomConfigStore'
import { useSseStore } from '@/store/sseStore'

const route = useRoute()
const router = useRouter()
const isCollapse = ref(false)
const activeSubmenu = ref('')
const roomConfigStore = useRoomConfigStore()
const sseStore = useSseStore()
const messageListRef = ref<HTMLElement>()
const hasUnreadMessages = ref(false)

// 获取当前机房
const currentRoom = computed(() => roomConfigStore.currentRoom)

const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value
}

// 处理子菜单展开
const handleSubmenuOpen = (index: string) => {
  activeSubmenu.value = index
}

// 处理切换/配置机房
const handleChangeRoom = () => {
  router.push('/settings/room-config')
}

// 获取消息图标
const getMessageIcon = (type: string) => {
  switch (type) {
    case 'success':
      return CircleCheckFilled
    case 'error':
      return CircleCloseFilled
    case 'warning':
      return WarningFilled
    default:
      return InfoFilled
  }
}

// 清空消息
const clearMessages = () => {
  sseStore.$patch((state) => {
    state.messages = []
  })
  hasUnreadMessages.value = false
}

// 监听新消息，自动滚动到底部
watch(
  () => sseStore.messages.length,
  async () => {
    hasUnreadMessages.value = true
    await nextTick()
    if (messageListRef.value) {
      messageListRef.value.scrollTop = messageListRef.value.scrollHeight
    }
  },
)

// 初始化SSE连接
onMounted(() => {
  console.log('App mounted, initializing SSE...')
  sseStore.initSSE()
})

// 组件销毁前断开SSE连接
onBeforeUnmount(() => {
  console.log('App unmounting, disconnecting SSE...')
  sseStore.disconnectSSE()
})
</script>

<template>
  <el-container class="app-container">
    <!-- 侧边栏 -->
    <el-aside :width="isCollapse ? '64px' : '220px'">
      <el-menu
        :default-active="route.path"
        class="el-menu-vertical"
        :router="true"
        :collapse="isCollapse"
        :unique-opened="true"
        @open="handleSubmenuOpen"
      >
        <div class="logo-container">
          <img src="@/assets/logo-text.png" alt="Logo" class="logo" />
        </div>
        <!-- 首页 -->
        <el-menu-item index="/">
          <el-icon><HomeFilled /></el-icon>
          <template #title>
            <span>首页</span>
          </template>
        </el-menu-item>

        <!-- 资产管理 -->
        <el-sub-menu index="/asset">
          <template #title>
            <el-icon><Platform /></el-icon>
            <span>资产管理</span>
          </template>
          <el-menu-item index="/asset/server">服务器管理</el-menu-item>
          <el-menu-item index="/asset/deploy">自动化部署</el-menu-item>
          <el-menu-item index="/asset/datacenter">机房管理</el-menu-item>
          <el-menu-item index="/asset/cabinet">机柜管理</el-menu-item>
        </el-sub-menu>

        <!-- SSH终端 -->
        <el-menu-item index="/ssh" >
          <el-icon><Platform /></el-icon>
          <template #title>
            <span>远程终端</span>
            <el-tag size="small" type="warning" class="dev-tag">开发中</el-tag>
          </template>
        </el-menu-item>

        <!-- 任务调度 -->
        <el-sub-menu index="/task">
          <template #title>
            <el-icon><Clock /></el-icon>
            <span>任务调度</span>
          </template>
          <el-menu-item index="/task/list">任务列表</el-menu-item>
          <el-menu-item index="/task/workflow">工作流管理</el-menu-item>
          <el-menu-item index="/task/scripts">脚本管理</el-menu-item>
        </el-sub-menu>

        <!-- 监控中心 -->
        <el-menu-item index="/monitor" disabled>
          <template #title>
            <el-icon><DataLine /></el-icon>
            <span>监控中心</span>
            <el-tag size="small" type="warning" class="dev-tag">开发中</el-tag>
          </template>
        </el-menu-item>

        <!-- 告警管理 -->
        <el-menu-item index="/alert" disabled>
          <template #title>
            <el-icon><Warning /></el-icon>
            <span>告警管理</span>
            <el-tag size="small" type="warning" class="dev-tag">开发中</el-tag>
          </template>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 主要内容区 -->
    <el-container>
      <!-- 顶部导航栏 -->
      <el-header class="header">
        <div class="left">
          <el-button type="text" @click="toggleSidebar">
            <el-icon :size="20">
              <Fold v-if="!isCollapse" />
              <Expand v-else />
            </el-icon>
          </el-button>
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }"> 首页 </el-breadcrumb-item>
            <el-breadcrumb-item v-if="route.meta.title">
              {{ route.meta.title }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="header-right">
          <el-popover
            placement="bottom-end"
            :width="300"
            trigger="click"
            popper-class="message-popover"
          >
            <template #reference>
              <el-badge :is-dot="hasUnreadMessages" class="message-badge">
                <el-button class="message-btn" :type="sseStore.isConnected ? 'success' : 'danger'">
                  <el-icon><Message /></el-icon>
                  实时消息
                  <span class="connection-status">{{
                    sseStore.isConnected ? '已连接' : '未连接'
                  }}</span>
                </el-button>
              </el-badge>
            </template>

            <div class="message-panel">
              <div class="message-header">
                <span class="title">实时消息</span>
                <el-button
                  v-if="sseStore.messages.length"
                  type="primary"
                  link
                  @click="clearMessages"
                >
                  清空消息
                </el-button>
              </div>
              <div class="message-list" ref="messageListRef">
                <template v-if="sseStore.messages.length">
                  <div
                    v-for="(message, index) in sseStore.messages"
                    :key="index"
                    class="message-item"
                    :class="message.type"
                  >
                    <el-icon class="message-icon">
                      <component :is="getMessageIcon(message.type)" />
                    </el-icon>
                    <span class="message-content">{{ message.message }}</span>
                  </div>
                </template>
                <el-empty v-else description="暂无消息" />
              </div>
            </div>
          </el-popover>
          <div class="room-config">
            <template v-if="currentRoom">
              <el-tag class="room-tag" type="info">
                <el-icon><Location /></el-icon>
                {{ currentRoom.room_name }}
              </el-tag>
              <el-button type="primary" link @click="handleChangeRoom"> 切换机房 </el-button>
            </template>
            <el-button v-else type="primary" @click="handleChangeRoom"> 配置机房 </el-button>
          </div>
          <el-dropdown>
            <span class="user-info">
              <el-avatar :size="32" icon="UserFilled" />
              <span>管理员</span>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>个人信息</el-dropdown-item>
                <el-dropdown-item>修改密码</el-dropdown-item>
                <el-dropdown-item divided>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <!-- 内容区 -->
      <el-main>
        <router-view></router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<style scoped lang="scss">
.app-container {
  height: 100vh;
  width: 100vw;
  overflow-x: hidden;
}

.el-aside {
  background-color: #304156;
  transition: width 0.3s;

  .logo-container {
    height: 64px;
    display: flex;
    align-items: center;
    padding: 0 20px;
    color: #fff;
    min-width: 200px;
    background-color: #2b2f3a;

    .logo {
      height: 46px;
      margin-right: 12px;
    }
  }

  .el-menu {
    border-right: none;
    background-color: transparent;

    :deep(.el-menu-item),
    :deep(.el-sub-menu__title) {
      color: #bfcbd9;
      height: 50px;
      line-height: 50px;

      &:hover {
        color: #fff;
        background-color: #263445;
      }

      &.is-active {
        color: #409eff;
        background-color: #263445;
      }
    }

    // 修改子菜单样式
    :deep(.el-sub-menu) {
      .el-menu {
        background-color: #1f2d3d;

        .el-menu-item {
          color: #a4b7cc;

          &:hover {
            color: #fff;
            background-color: #263445;
          }

          &.is-active {
            color: #409eff;
            background-color: #263445;
          }
        }
      }
    }
  }
}

.el-header {
  height: 64px !important;
  background-color: #fff;
  border-bottom: 1px solid #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;

  .left {
    display: flex;
    align-items: center;
    gap: 20px;

    .el-button {
      font-size: 20px;
      height: 64px;
      padding: 0 12px;
    }

    .el-breadcrumb {
      font-size: 14px;
    }
  }

  .header-right {
    display: flex;
    align-items: center;
    gap: 16px;

    .message-badge {
      :deep(.el-badge__content.is-dot) {
        right: 5px;
        top: 5px;
      }
    }

    .message-btn {
      display: inline-flex;
      align-items: center;
      gap: 4px;

      .connection-status {
        font-size: 12px;
        margin-left: 4px;
      }
    }

    .room-config {
      display: flex;
      align-items: center;
      gap: 12px;

      .room-tag {
        display: flex;
        align-items: center;
        gap: 4px;
        padding: 6px 12px;

        .el-icon {
          margin-right: 4px;
        }
      }
    }

    .user-info {
      display: flex;
      align-items: center;
      gap: 12px;
      cursor: pointer;

      .el-avatar {
        width: 36px;
        height: 36px;
      }

      span {
        font-size: 14px;
      }
    }
  }
}

.el-main {
  background-color: #f0f2f5;
  padding: 24px;
  min-height: calc(100vh - 64px);

  :deep(.home-container) {
    max-width: 1440px;
    margin: 0 auto;
    padding: 0;

    @media (max-width: 1440px) {
      padding: 0 24px;
    }

    @media (min-width: 1920px) {
      max-width: 1800px;
    }
  }
}

.dev-tag {
  margin-left: 8px;
  transform: scale(0.8);
  font-weight: normal;
}

:deep(.el-menu-item.is-disabled) {
  opacity: 0.8;
  cursor: not-allowed;

  &:hover {
    background-color: transparent !important;
  }

  .el-icon {
    color: var(--el-text-color-disabled);
  }
}

.message-popover {
  padding: 0;

  .message-panel {
    display: flex;
    flex-direction: column;
    height: 400px;

    .message-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 16px;
      border-bottom: 1px solid var(--el-border-color-lighter);

      .title {
        font-weight: 500;
        color: var(--el-text-color-primary);
      }
    }

    .message-list {
      flex: 1;
      overflow-y: auto;
      padding: 12px;

      .message-item {
        display: flex;
        align-items: flex-start;
        gap: 8px;
        padding: 8px;
        margin-bottom: 8px;
        border-radius: 4px;
        background: var(--el-fill-color-light);

        &:last-child {
          margin-bottom: 0;
        }

        .message-icon {
          margin-top: 2px;
        }

        &.success {
          background: var(--el-color-success-light-9);
          .message-icon {
            color: var(--el-color-success);
          }
        }

        &.error {
          background: var(--el-color-danger-light-9);
          .message-icon {
            color: var(--el-color-danger);
          }
        }

        &.warning {
          background: var(--el-color-warning-light-9);
          .message-icon {
            color: var(--el-color-warning);
          }
        }

        &.notification {
          background: var(--el-color-info-light-9);
          .message-icon {
            color: var(--el-color-info);
          }
        }

        .message-content {
          flex: 1;
          font-size: 13px;
          line-height: 1.4;
          word-break: break-all;
        }
      }
    }
  }
}
</style>
